export default {
	namespaced: true,
	// state: () => ({
	// 	cart: []
	// }),
	state: {
		cart: JSON.parse(uni.getStorageSync("cart") || "[]")
	},
	mutations: {
		ADDTOCART(state, goods) {
			state.cart.push(goods)
		},
		UPDATECART(state, findResult) {
			findResult.goods_count++
		},
		DELETECART(state,  goodsIdx) {
			state.cart.splice(goodsIdx, 1)
			uni.setStorageSync("cart", JSON.stringify(state.cart))
		},
		UNCHECKEDALL(state) {
			state.cart.map(item => {
				item.goods_state = false
			})
			uni.setStorageSync("cart", JSON.stringify(state.cart))
		},
		CHECKEDALL(state) {
			state.cart.map(item => {
				item.goods_state = true
			})
			uni.setStorageSync("cart", JSON.stringify(state.cart))
		}
	},
	actions: {
		addToCart({commit,state}, goods) {
			const findResult = state.cart.find(item => item.goods_id == goods.goods_id)
			if(!findResult) {
				commit("ADDTOCART", goods)
			} else {
				commit("UPDATECART", findResult)
			}
			uni.setStorageSync("cart", JSON.stringify(state.cart))
		},
		updateCart({commit,state}) {
			uni.setStorageSync("cart", JSON.stringify(state.cart))
		},
		deleteGoods({commit, state}, goods_id) {
			
			let goodsIdx = state.cart.findIndex(item => {
				return item.goods_id == goods_id
			})
			console.log(goodsIdx)
			if(goodsIdx != -1) {
				commit("DELETECART", goodsIdx)
			}
		}
	},
	getters: {
		checkedGoodsAmount(state) {
			return state.cart.filter(item => item.goods_state == true).reduce((acc,curr) => {
				acc += curr.goods_count * curr.goods_price
				return acc
			}, 0)
		},
		isAllChecked(state) {
			return state.cart.every(item => item.goods_state == true)
		},
		checkedCount(state) {
			return state.cart.filter(item => item.goods_state).reduce((acc, curr) => acc += curr.goods_count, 0)
		},
		total(state) {
			return state.cart.reduce((acc,curr) => {
				acc += curr.goods_count
				return acc
			}, 0)
		}		
	}
}